package com.yx.frame.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.yx.frame.authority.AuthorityManager;
import com.yx.frame.authority.User;
import com.yx.frame.log.LogFactory;
import com.yx.frame.log.LogWriter;
import com.yx.frame.server.Application;
import com.yx.frame.service.Action;
import com.yx.frame.service.ActionManager;
import com.yx.frame.service.ServiceError;
import com.yx.frame.service.ServiceResult;
import com.yx.frame.util.ExportExcel;

public final class HttpFileDownloadServletJre6 extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4857033641193767395L;
	protected static LogWriter log = LogFactory.getInstance().getLogWriter();
	static final String CONTENT_TYPE = "text/html; charset=utf-8";
	public HttpFileDownloadServletJre6() {
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		handler(request, response);

	}

	/**
	 * 对应导出Excel
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		handlerExcel(request, response);
	}
	
	public static final void handlerExcel(HttpServletRequest request, HttpServletResponse response) {
		int action = -1;//ACTION_ID
		String serviceName = null;
		ServiceError error = new ServiceError();
		User user = null;
		ServiceResult returnJsonObject = null;
		String Header = null;
		String JsonDataFormat = null;
		String FileName = null;
		String title = null;
		String Processer = null;
		String HeaderMergedRegion = null;
		String ColumnData = null;
		try {
			String RequestData = URLDecoder.decode(request.getParameter("RequestData"), "utf-8");//Action执行需要的JsonObject
			String ActionId = URLDecoder.decode(request.getParameter("ActionId"), "utf-8");
			if(ActionId != null){
				action = Integer.parseInt(ActionId);
			}
			HeaderMergedRegion = URLDecoder.decode(request.getParameter("HeaderMergedRegion"), "utf-8");
			ColumnData = URLDecoder.decode(request.getParameter("ColumnData"), "utf-8");
			FileName = URLDecoder.decode(request.getParameter("FileName"), "utf-8");
			title = URLDecoder.decode(request.getParameter("Title"), "utf-8");
			Header = URLDecoder.decode(request.getParameter("Header"), "utf-8");
			String UId = request.getParameter("UId");
			JsonDataFormat =  URLDecoder.decode(request.getParameter("JsonDataFormat"), "utf-8");
			Processer = URLDecoder.decode(request.getParameter("Processer"), "utf-8");
			JSONObject requestJSONData = new JSONObject(RequestData);
			
			user = getCurrentUser(UId, error);
			if (error.isError())return;
			if(action>=0){
				Action permitAction = user.getPermitedAction(action, error);
				if (error.isError())return;
				serviceName =  permitAction.getService() + "/" + permitAction.getMethod();
				returnJsonObject = permitAction.doActionMethod(user, requestJSONData, error);
			}else{
				returnJsonObject = getSystemActions(requestJSONData,error);
			}			
			
			if(!error.isError()){
				debug(user, serviceName, "返回JSON:" + returnJsonObject);
				//writeResponse(response, returnJsonObject);			
			}
			
			//System.out.println(returnJsonObject);
		} catch (Exception e) {
			e.printStackTrace();
			error.setErrorMessage(e.getMessage());
			writeResponse(response, error);	
		}
		
		try{
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-Type","application/msexcel");
			response.setHeader("Content-Disposition","attachment;filename=" + new String(FileName.getBytes("GB2312"), "ISO-8859-1"));
			response.setContentType(ContentTypeUtil.getContentType(FileName));
			
			OutputStream out = response.getOutputStream();
			InputStream in = null;
			try {
				JSONArray header = new JSONArray(Header);
				JSONArray headerMergedRegion = new JSONArray(HeaderMergedRegion);
				JSONArray columnData = new JSONArray(ColumnData);
				JSONArray ja = new JSONArray(JsonDataFormat);
				JSONObject datas = null;
				JSONArray rows = null;
				
				if("true".equals(Processer)){
					Application.getProvider().processRow(action, returnJsonObject);
				}else{
					for (short i = 0; i < ja.length(); i++) {
						JSONObject headerObj = ja.getJSONObject(i);
						String jsonType = headerObj.getString("jsonType");
						String jsonKey = headerObj.getString("jsonKey");
						
						if("JSONObject".equals(jsonType)){
							if(i == 0){
								datas = returnJsonObject.getJSONObject(jsonKey);
							}else{
								datas = datas.getJSONObject(jsonKey);
							}
						}else{
							rows = returnJsonObject.getJSONArray(jsonKey);
						}
					}
				}
				
				
				
				//ExportExcel.exportExcel(Title, header, rows, out);
				ExportExcel.exportExcel(title, header, headerMergedRegion, columnData, rows, out, error);
			}catch (Exception e) {
				e.printStackTrace();
				error.setErrorMessage(e.getMessage());
				//writeResponse(response, error);	
			} finally {
				if (out != null){
					out.close();
				}
				if (in != null){
					in.close();
				}
			}
			
			//System.out.println("返回JSON:" + returnJsonObject);
		} catch (Throwable e) {
			e.printStackTrace();
			error.setErrorMessage(e.getMessage());
			//writeResponse(response, error);	
		}finally {
			if (error.isError()){
				error(user, serviceName, "返回JSON:" + error);
				writeResponse(response, error);	
			}
		}
	}

	public static final void handler(HttpServletRequest request,
			HttpServletResponse response) {
		long t = System.currentTimeMillis();
		ServiceError error = new ServiceError();
		User user = null;
		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			user = getCurrentUser(request, error);
			String fileName = URLDecoder.decode(request.getParameter("File"), "UTF-8");
			int start = fileName.lastIndexOf("\\");
			String _fileName = fileName.substring(start + 1);
			String _fileName_ZH = new String(_fileName.getBytes("GB2312"),"ISO8859_1");
			response.setHeader("Content-Disposition","attachment;filename=" + _fileName_ZH + "");
			response.setContentType(ContentTypeUtil.getContentType(fileName));
			OutputStream out = response.getOutputStream();
			Application.getProvider().readFile(fileName, out);
		} catch (Exception e) {
			error.setErrorMessage(e.getMessage());
		} finally {
			if (error.isError()) {
				error(user, "FileDownload", error.getErrorMessage());
			}
			debug(user, "FileDownload", "耗时："
					+ (System.currentTimeMillis() - t) + "毫秒！");
		}
	}
	
	private static final User getCurrentUser(String uID, ServiceError error) throws Exception {
		//return new User("21307000528","21307000528","123","11111111111111111111111");
		try {
			return AuthorityManager.getInstance().authentication(uID, error);
		} catch (Exception e) {
			error.setErrorMessage("非法的用户认证信息:"+e.getMessage());
			return null;
		}		
	}

	private static final User getCurrentUser(HttpServletRequest request,
			ServiceError error) throws Exception {
		String uID = null;
		try {
			uID = request.getParameter("UId");
			return AuthorityManager.getInstance().authentication(uID, error);
		} catch (Exception e) {
			error.setErrorMessage("非法的用户认证信息:" + e.getMessage());
			return null;
		}
	}
	
	public static final ServiceResult getSystemActions(JSONObject requestJSONData,ServiceError error)throws Exception{
		ServiceResult returnObj = new ServiceResult();
		String isPerformanceMonitor="0";
		try{
			isPerformanceMonitor=requestJSONData.getString("IsPerformanceMonitor");
		}catch(Exception e){}
		if("1".equals(isPerformanceMonitor)){
			ActionManager.setPerformanceMonitor(true);	
		}else if("0".equals(isPerformanceMonitor)){
			ActionManager.setPerformanceMonitor(false);	
		}
		Action[] actionList=ActionManager.getInstace().listActions();
		JSONArray actionsJsonArray=new JSONArray();
		for(int i=0;i<actionList.length;i++){
			Action act=actionList[i];
			JSONObject row=new JSONObject();
			row.put("ID", act.getId());
			row.put("NAME", act.getName());
			row.put("COMMENT", act.getComment());
			row.put("TOTAL_TIME", act.getTotalAccessTime());
			row.put("TOTAL_ACCESS", act.getTotalAccessNumber());
			actionsJsonArray.put(row);
		}
		returnObj.put("ACTIONS", actionsJsonArray);
		return returnObj;
    }
	
	public static void writeResponse(HttpServletResponse response, ServiceResult serviceResult) {
		try {
			response.setContentType(CONTENT_TYPE);
			// response.setContentType("<meta http-equiv=\"Access-Control-Allow-Origin\" content=\"*\">");
			response.setHeader("Access-Control-Allow-Origin", "*");
			PrintWriter out = response.getWriter();
			if (serviceResult == null) {
				ServiceError error = new ServiceError("返回为空");
				out.println(error.toString());
			} else {
				out.println(serviceResult.toString());
			}
			out.flush();
		} catch (Exception e) {
		}
		// out.close();
	}

	public static void error(User user, String serviceName, String logMsg) {
		log.error(user, serviceName, logMsg);
	}

	public static void debug(User user, String serviceName, String logMsg) {
		log.debug(user, serviceName, logMsg);
	}
}
